package com.reggie.web;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.pojo.Orders;
import com.reggie.pojo.Setmeal;
import com.reggie.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private IOrdersService ordersService;

    @Value("${reggie.outPath}")
    private String outPath;

    @PostMapping("/submit")
    public R<String> submitOrder(@RequestBody Orders orders){
        log.info("提交订单");
        ordersService.submit(orders);
        return R.success("清空购物车成功");
    }

    @GetMapping("/userPage")
    public R<Page> userPage(Integer page,Integer pageSize){
        Page pageBean = new Page(page, pageSize);

        ordersService.page(pageBean);

        return R.success(pageBean);
    }

    @GetMapping("/page")
    public R orderPage(Integer page, Integer pageSize, String number,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date beginTime,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date endTime){
        Page<Orders> pageBean = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(number),Orders::getNumber,number);
        if (beginTime != null){
            lqw.between(Orders::getOrderTime,beginTime,endTime);
        }
        lqw.orderByDesc(Orders::getOrderTime);

        ordersService.page(pageBean,lqw);
        return R.success(pageBean);
    }

    @GetMapping("/export")
    public R exportOrders(){
        List<Orders> list = ordersService.list();
        String fileName = outPath+"瑞吉订单统计表"+System.currentTimeMillis()+".xlsx";
        EasyExcel.write(fileName,Orders.class).sheet("瑞吉订单").doWrite(list);
        return R.success("导出成功");
    }
}
